/**
 * 
 */
package cn.iwoo.svn.util;

import java.io.File;

import org.tigris.subversion.svnclientadapter.ISVNClientAdapter;
import org.tigris.subversion.svnclientadapter.SVNClientAdapterFactory;
import org.tigris.subversion.svnclientadapter.SVNRevision;
import org.tigris.subversion.svnclientadapter.SVNUrl;
import org.tigris.subversion.svnclientadapter.javahl.JhlClientAdapterFactory;

/**
 * @author lggege
 */
public class SVNRepositoryUtil {
	public static SVNRepositoryUtil instance = new SVNRepositoryUtil();

	public static SVNRepositoryUtil getInstance() {
		return instance;
	}

	private static boolean HAS_INIT = false;

	private SVNRepositoryUtil() {
		this.init();
	}

	/**
	 * do init
	 */
	public void init() {
		if (!HAS_INIT) {
			this.registerSvnClientAdapterFactory();
			HAS_INIT = true; // Never register again
		}
	}

	/**
	 * register SVN client liberary
	 */
	private void registerSvnClientAdapterFactory() {
		try {
			JhlClientAdapterFactory.setup();
			// CmdLineClientAdapterFactory.setup();
			// SvnKitClientAdapterFactory.setup();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * create a svn client
	 */
	private ISVNClientAdapter createSvnClient(SVNRepositoryInfo repositoryInfo) throws Exception {
		String bestClientType = SVNClientAdapterFactory.getPreferredSVNClientType();
		ISVNClientAdapter svnClient = SVNClientAdapterFactory.createSVNClient(bestClientType);

		if (repositoryInfo.getUserName() != null) {
			svnClient.setUsername(repositoryInfo.getUserName());
		}
		if (repositoryInfo.getPassword() != null) {
			svnClient.setPassword(repositoryInfo.getPassword());
		}

		svnClient.addNotifyListener(new SVNNotifyListener());

		return svnClient;
	}

	public void checkout(SVNRepositoryInfo repositoryInfo, String moduleName, File destPath, SVNRevision revision, boolean recurse) throws Exception {
		ISVNClientAdapter svnClient = this.createSvnClient(repositoryInfo);
		if (!destPath.exists()) {
			destPath.mkdirs();
		}

		if (moduleName == null) {
			moduleName = "";
		}
		SVNUrl moduleUrl = new SVNUrl(repositoryInfo.getUrl() + moduleName);
		svnClient.checkout(moduleUrl, destPath, revision, true);
	}
}
